package com.lr.app.application;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

import com.ws.commons.tool.StrTool;

public class MySession {

	private final String id;
	private SessionSubject loginUser;
	private boolean isLogin;
	private Map<String, Object> attributes;
	private LocalDateTime lastActiveTime;

	public SessionSubject getLoginUser() {
		return loginUser;
	}

	public Map<String, Object> getAttributes() {
		return attributes;
	}

	public String getId() {
		return id;
	}

	public void setAttribute(String attrName, Object val) {
		attributes.put(attrName, val);
	}

	public Object getAttribute(String attrName) {
		return attributes.get(attrName);
	}

	public LocalDateTime getLastActiveTime() {
		return lastActiveTime;
	}

	public boolean isLogin() {
		return isLogin;
	}

	void login(SessionSubject loginUser) {
		if (!this.isLogin) {
			this.isLogin = true;
			this.loginUser = loginUser;
		}
	}

	 void active() {
		this.lastActiveTime =LocalDateTime.now();
	}
	MySession() {
		this.id = StrTool.getUUId();  
		this.lastActiveTime = LocalDateTime.now();
		this.attributes = new HashMap<>();
	}

	
	/**
	  * 更新用户信息
	 * 
	 * @param loginUser
	 */
	public synchronized void updateLoginUser(SessionSubject loginUser) {
		if (this.loginUser == null || !(this.loginUser.getId().equals(loginUser.getId()))) {
			throw new RuntimeException("用户未登录，或者不是同一个用户");
		}
		this.loginUser = loginUser;
	}


}
